package com.example;

import java.io.File;
import java.io.IOException;
import java.net.URI;

import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

public class Main {
	public static final String BASE_URI = "http://localhost:8087/myapp/";

	public static HttpServer startServer() {
		final ResourceConfig rc = new ResourceConfig().packages("com.example");
		return GrizzlyHttpServerFactory.createHttpServer(URI.create(Main.BASE_URI), rc);
	}

	public static void main(String[] args) throws IOException {
		final HttpServer server = Main.startServer();
		//System.out.println(String.format("Jersey app started with WADL available at " + "%sapplication.wadl\nHit enter to stop it...", Main.BASE_URI));
		//System.in.read();
		//server.shutdownNow();
		 FileRepositoryBuilder builder = new FileRepositoryBuilder();

	        Repository repository = builder
	                .setGitDir(new File("C:\\temp\\git\\.git")).readEnvironment()
	                .findGitDir().build();

	        listRepositoryContents(repository);

	        // Close repo
	        repository.close();
	}
	 private static void listRepositoryContents(Repository repository) throws IOException {

	        Ref head = repository.getRef("HEAD");

	        // a RevWalk allows to walk over commits based on some filtering that is
	        // defined
	        RevWalk walk = new RevWalk(repository);

	        RevCommit commit = walk.parseCommit(head.getObjectId());
	        RevTree tree = commit.getTree();
	        System.out.println("Having tree: " + tree);

	        // now use a TreeWalk to iterate over all files in the Tree recursively
	        // you can set Filters to narrow down the results if needed
	        TreeWalk treeWalk = new TreeWalk(repository);
			treeWalk.addTree(tree);
			treeWalk.setRecursive(false);
			while (treeWalk.next()) {
			    if (treeWalk.isSubtree()) {
			        System.out.println("dir: " + treeWalk.getPathString());
			        treeWalk.enterSubtree();
			    } else {
			        System.out.println("file: " + treeWalk.getPathString());
			    }
			}

	    }
}